<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane label="工艺管理" name="first">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="工艺编号" prop="cftSn">
            <el-input
              v-model="queryParams.cftSn"
              placeholder="请输入工艺编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-if="$route.query.cftId==null"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mes:craft:add']"
            >新增工艺</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['mes:deliver:export']"
            >导出</el-button>
          </el-col>
<!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
        </el-row>

        <el-table v-loading="loading" :data="craftList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="序号" align="center" prop="number" width="90"/>
          <el-table-column label="工艺状态" align="center" prop="cftState" width="90">
            <template v-slot = "scope">
              <dict-tag :options="dict.type.craft_state" :value="scope.row.cftState"/>
            </template>
          </el-table-column>
          <el-table-column label="工艺编号" align="center" prop="cftSn" />
          <el-table-column label="工艺名称" align="center" prop="cftName" />
          <el-table-column label="创建者" align="center" prop="createdBy" />
          <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:craft:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mes:craft:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改工艺管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item v-if="this.$route.query.productId==null && form.proId==null" label="产品" prop="proId">
              <el-select v-model="form.proId" placeholder="请选择" style="width:30%" @change="handleProductChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="`${item.proName}/${item.proSn}`"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-else label="产品" prop="proId">
              <span>{{form.proName + '/' + form.proSn}}</span>
            </el-form-item>
            <el-row>
              <el-col :span="8">
                <el-form-item label="产品名称:" prop="proName">
                  <span>{{ form.proName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品编码:" prop="proSn">
                  <span>{{ form.proSn }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品类型:" prop="proType">
                  <span>{{ proTypeMap[form.proType] }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="工艺名称" prop="cftName">
              <el-input v-model="form.cftName" placeholder="请输入工艺名称" style="width: 30%;"/>
            </el-form-item>
            <el-form-item label="选择物料" prop="materId ">
              <el-select v-model="form.materId" filterable placeholder="请选择" style="width: 30%;" @change="handleMaterialChange">
                <el-option
                  v-for="item in matList"
                  :key="item.id"
                  :label="item.proMateriel.matName"
                  :value="item.matId">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="工序列表" >
              <el-button style="margin-bottom: 10px;" type="primary" @click="prcmtradd(count)">添 加</el-button>
              <el-card shadow="always" style="border-radius: 15px;">
                <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.prc">
                  <el-table-column label="工序顺序" align="center" prop="processSeq">
                    <template slot-scope="scope">
                      {{ scope.row.processSeq }}
                    </template>
                  </el-table-column>
                  <el-table-column label="物料" align="center" prop="matName">
                    <template slot-scope="scope">
                      {{ scope.row.matName }}
                    </template>
                  </el-table-column>
                  <el-table-column label="工序名称" align="center" prop="pcsname">
                    <template slot-scope="scope">
                      {{ scope.row.pcsName }}
                    </template>
                  </el-table-column>
                  <el-table-column label="选择工序" align="center" prop="id">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.processId" filterable placeholder="请选择"
                                 @change="(option) => prcchang(option,scope.$index)">
                        <el-option
                          v-for="item in processList"
                          :key="item.id"
                          :label="`${item.pcsName}/${item.id}`"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <!--                    <el-button size="mini" type="text" icon="el-icon-edit" @click="prcmtradd(scope.$index, scope.row)"-->
                      <!--                               v-hasPermi="['mes:proinfo:edit']">增加</el-button>-->
                      <el-button size="mini" type="text" icon="el-icon-delete" @click="prcmtrdel(scope.$index)"
                                 v-hasPermi="['mes:proinfo:remove']">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </el-card>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-tab-pane>
    <el-tab-pane label="工序管理" name="second">
      <child1 v-if="isChildUpdate2"></child1>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { listCraft, getCraft, delCraft, addCraft, updateCraft, getCraftProcess } from "@/api/mes/craft";
import {listProcess} from "@/api/mes/process";
import {getBomMat} from "@/api/mes/bom";
import {listPro_design} from "@/api/mes/pro_design";
import firstComponent from "../process/index"
import Vue from "vue";
;

export default {
  name: "Craft",
  components: {
    child1: firstComponent,
  },
  dicts:["craft_state"],
  data() {
    return {
      // 默认第一个选项卡
      activeName: 'first',
      // 初始化两个变量 isChildUpdate1:true，isChildUpdate2:false；
      // 使用v-if控制child1和child2是否渲染。
      // 每次切换tab选项的时候，触发事件。让当前点击的tab变量设置位true，让当前组件重新渲染。
      // 这时候当你来回切换的时候，通过v-if判断是否重新渲染当前组件
      isChildUpdate2: true,
      //行数
      count:0,
      //顺序记录
      seqCount:1,
      //记录probomid
      probomid:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工艺管理表格数据
      craftList: [],
      // 工序管理表格数据
      processList: [],
      // 产品管理表格数据
      productOptions: [],
      //存储物料下拉框的id，物料名
      selectedMaterial:[],
      // bom管理表格数据
      bomList: [],
      //物料管理表格数据
      matList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 工艺查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cftSn: null,
      },
     // 工序查询参数
      queryParamsProcess: {
        // pageNum: 1000,
        // pageSize: 10,
        pcsSn: null,
        pcsName: null,
      },
      // 产品查询参数
      queryParamsProduct: {
        // pageNum: 1000,
        // pageSize: 10,
        proSn: null,
        proName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 产品分类映射
      proTypeMap: {
        0: '成品',
        1: '半成品',
        2:'原材料',
      },
      //工序行数计数
      rowCounter: 0,
    };
  },
  created() {
    this.getList();
    this.getProcessList();
    this.getProductList();
  },
  watch: {
    '$route.query.productId' (to, from) { //监听路由是否变化
      if(this.$route.path == '/pro/craft'){//仅在当前页面生效
        if(to != from){
          // this.queryParams.taskId = to;
          this.getList();//重新加载数据
        }
      }
    }
  },
  methods: {
    handleClick (tab) {
      if (tab.name === 'second') {
        this.isChildUpdate2 = true
      } else if (tab.name === 'first') {
        this.isChildUpdate2 = false
      }
    },
    /**
     * 删除物料
     * @param {下标} index
     */
    prcmtrdel(index) {
      this.form.prc.splice(index, 1)
      this.count=this.count-1;
      this.seqCount=this.seqCount-1;
    },

    /**
     * 添加物料
     * @param {下标} index
     * @param {行数据} row
     */
    prcmtradd(index) {
      if (index != undefined) {
        this.form.prc.splice(index, 0,
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            id:null,
            remark: null,
            matId: null,
            matSn: null,
            matPrice: 0,
            pcsName:null,
            processSeq:this.seqCount,
            processId: null,
          })
      }
      else {
        this.form.prc.push(
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            processId: null,
            houId: null,
            id:null,
            matId: null,
            matName: null,
            matSn: null,
            matPrice: 0,
            pcsName:null,
            processSeq:this.count+1,
          })
      }
      this.count=this.count+1;
      this.seqCount=this.seqCount+1;
    },
    handleProductChange() {
      // 根据 form.proId 找到对应的存址
      this.form.proId = parseInt(this.form.proId);
      const selectedProduct = this.productOptions.find(option => option.id === this.form.proId);
      if (selectedProduct) {
        // 更新其他输入框的值
        this.form.proSn= selectedProduct.proSn;
        this.form.proName=selectedProduct.proName;
        this.form.proType=selectedProduct.proType;
        this.probomid=Number(selectedProduct.proBomId);
        this.getMatList();
      }
    },
    handleMaterialChange(materialId) {
      // 找到选中的物料对象
      this.selectedMaterial = this.matList.find(item => item.matId === materialId);
      // 更新表单中的物料ID
      this.form.materId = materialId;
      //新增一行工序，并将选中的物料字段显示在新行中
      if(this.count==0){
          this.form.prc.push({
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            processId: null,
            houId: null,
            id:null,
            // 将选择的物料字段赋给工序列表中的matName属性
            matId:this.selectedMaterial.matId,
            matName: this.selectedMaterial.proMateriel.matName,
            matSn: null,
            matPrice: 0,
            pcsName:null,
            processSeq:this.seqCount,
          });

          this.count=this.count+1;
          this.seqCount=this.seqCount+1;
        }
      else{
          if(this.form.prc[this.count-1].matName!=null)
          {
            this.form.prc.push({
              createBy: "",
              createTime: "",
              updateBy: "",
              updateTime: null,
              remark: null,
              id:null,
              processId: null,
              houId: null,
              // 将选择的物料字段赋给工序列表中的matName属性
              matId:this.selectedMaterial.matId,
              matName: this.selectedMaterial.proMateriel.matName,
              matSn: null,
              matPrice: 0,
              pcsName:null,
              processSeq:this.seqCount,
            });

            this.count=this.count+1;
            this.seqCount=this.seqCount+1;
          }
          else{
            // this.form.prc[this.count-1].matName=this.selectedMaterial.proMateriel.matName;
            Vue.set(this.form.prc[this.count - 1], 'matName', this.selectedMaterial.proMateriel.matName);
            Vue.set(this.form.prc[this.count - 1], 'matId', this.selectedMaterial.matId);
          }
        }
    },

    prcchang(option, index) {
      let ss = this.processList.find(item => item.id == option)
      this.form.prc[index].pcsName = ss.pcsName;
    },
    /** 查询工序管理列表 */
    getProcessList() {
      listProcess(this.queryParamsProcess).then(response => {
        this.processList = response.rows;
      });
    },
    /** 列表编号 */
    calculateIndex() {
      this.craftList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    /** 查询产品管理列表 */
    getProductList() {
      listPro_design(this.queryParamsProduct,{ refresh: true }).then(response => {
        this.productOptions = response.rows;
        if(this.$route.query.productId){
          this.productOptions = this.productOptions
        }
        else {
          this.productOptions = this.productOptions.filter(item => item.proBomId !== null && item.cftId === null)
        }
      });
    },
    /** 查询bom管理列表 */
    getMatList() {
      getBomMat(this.probomid).then(response => {
        this.matList = response;
        console.log("14684",this.matList)
      });
    },
    /** 查询工艺管理列表 */

    getList() {
      this.loading = true;
      listCraft(this.queryParams).then(response => {
        this.craftList = response.rows;
        if(this.$route.query.cftId!=null){
          const cftId = parseInt(this.$route.query.cftId)
          this.craftList=this.craftList.filter(item=>item.id===cftId)
        }
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cftSn: null,
        cftName: null,
        cftState: null,
        remark: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        proSn: null,
        proName: null,
        proType: null,
        prc:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增工艺";
      //如果路由参数存在
      if (this.$route.query.productId) {
        this.form.proId = this.$route.query.productId;
        this.handleProductChange();
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCraft(id).then(response => {
        this.form = response.data;

      });
      getCraftProcess(id).then(response => {
        this.form.prc = response;
        this.count= response.length;
        this.handleProductChange();
        this.form.prc.forEach((item,index)=>{
          item.matName=this.matList[index].proMateriel.matName;
        })
        this.open = true;
        this.title = "修改工艺";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCraft(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCraft(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const cftName = row.cftName || this.cftName
      this.$modal.confirm('是否确认删除工艺名称为"' + cftName + '"的数据项？').then(function() {
        return delCraft(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/craft/export', {
        ...this.queryParams
      }, `craft_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
